import { Provide, Inject, Post, Body, Get } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Column, Entity, PrimaryGeneratedColumn, Repository, CreateDateColumn } from 'typeorm';

/**
 * 商品分类表
 */
@Entity('goods_category')
export class CategoryEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', length: 64, comment: '名称' })
  name: string;

  @Column({ type: 'int', nullable: true, comment: '父类ID', default: 0 })
  parentId: number;

  @Column({ type: 'text', nullable: true, comment: '说明' })
  description: string;

  @Column({ type: 'varchar', length: 255, nullable: true, comment: '图片URL' })
  image: string;

  @Column({ type: 'int', default: 0, comment: '排序' })
  sort: number;

  @Column({ type: 'int', comment: '所属分站ID' })
  siteId: number;  // 新增字段：所属分站ID

  @CreateDateColumn({ type: 'timestamp', comment: '创建时间' })
  createTime: Date;
}

@Provide()
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: CategoryEntity,
})
export class CategoryController extends BaseController {

  @InjectEntityModel(CategoryEntity)
  categoryRepo: Repository<CategoryEntity>;

  /**
   * 分类树结构
   */
  @Get('/tree')
  async tree() {
    // 1. 获取全部分类
    const all = await this.categoryRepo.find({ order: { sort: 'ASC', id: 'ASC' } });

    // 2. 构建树形结构
    function buildTree(list, parentId = 0) {
      return list
        .filter(item => item.parentId === parentId)
        .map(item => ({
          ...item,
          children: buildTree(list, item.id)
        }));
    }

    const tree = buildTree(all, 0);

    return this.ok(tree);
  }
}
